const jwt = require('jsonwebtoken');
const { User } = require('../models');

const auth = async (req, res, next) => {
  try {
    const token = req.header('Authorization')?.replace('Bearer ', '');
    
    if (!token) {
      throw new Error('未提供token');
    }

    const decoded = jwt.verify(token, process.env.JWT_SECRET);

    // 如果是管理员token
    if (decoded.isAdmin) {
      req.token = token;
      req.user = {
        id: 0,
        username: 'admin',
        nickname: '管理员',
        isAdmin: true
      };
      return next();
    }

    // 如果是普通用户token
    const user = await User.findOne({ where: { id: decoded.id } });
    if (!user) {
      throw new Error('用户不存在');
    }

    req.token = token;
    req.user = user;
    next();
  } catch (error) {
    res.status(401).json({ 
      code: 1,
      message: error.message || '请先登录'
    });
  }
};

module.exports = auth; 